import requests
import json
import base64
import urllib
from selenium import webdriver
import time


#selenium 截图
driver = webdriver.Chrome()
driver.get('https://www.dianxiaomi.com/index.htm')
time.sleep(1)

#删除元素
js = "var elem = document.getElementsByClassName('dnf');elem[0].parentNode.removeChild(elem[0]);"
driver.execute_script(js)

js = "var elem = document.getElementsByClassName('qqshow');elem[0].parentNode.removeChild(elem[0]);"
driver.execute_script(js)

js = "var elem = document.getElementsByClassName('QR');elem[0].parentNode.removeChild(elem[0]);"
driver.execute_script(js)


nodes = driver.find_element_by_id('loginImgVcode')
nodes.screenshot('test.png')

#用户名 exampleInputName exampleInputPassword

driver.find_element_by_id('exampleInputName').send_keys('18231327142')

driver.find_element_by_id('exampleInputPassword').send_keys('Xw1995410')


#请求百度api接口

res = requests.get("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=X4zQnKcx3oeNP8avL4Qmvrbw&client_secret=jAzondIDW9SoveGxdBd0UFAnw7i3rzXu")

res = json.loads(str(res.text))
token = res['access_token']

temp_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + token
temp_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
temp_file = open('./test.png', 'rb')
temp_image = temp_file.read()
temp_file.close()
temp_data = {'image': base64.b64encode(temp_image)}
temp_data = urllib.parse.urlencode(temp_data)
temp_res = requests.post(url=temp_url, data=temp_data, headers=temp_headers)

res = json.loads(str(temp_res.text))
print(res)
code = res['words_result'][0]['words']


driver.find_element_by_id('loginVerifyCode').send_keys(code.strip().replace(' ',''))

#登录按钮
driver.find_element_by_id('loginBtn').click()



time.sleep(5)


cookie = driver.get_cookies()
print(cookie)
jsonCookies = json.dumps(cookie)
with open('mycookie.json', 'w') as f:
    f.write(jsonCookies)

driver.close()